package com.borqs.samples;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class DataContentProvider extends ContentProvider {

    private static HashMap<String, String> mAlarmProjectionMap;
    private static HashMap<String, String> mWakelockProjectionMap;
    private static HashMap<String, String> mProcessProjectionMap;

    private static final int ALARM = 1;
    private static final int ALARM_ID = 2;

    private static final int WAKELOCK = 3;
    private static final int WAKELOCK_ID = 4;

    private static final int PROCESS = 5;
    private static final int PROCESS_ID = 6;

    private static final UriMatcher mUriMatcher;

    private DBHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = new DBHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy = null;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理

        case ALARM_ID:
            selectionArgs = setIdWhere(qb, uri,
                    DBProvider.AlarmSamplesTable._ID, selectionArgs);
        case ALARM:
            setQueryProperties(qb, mAlarmProjectionMap,
                    DBProvider.AlarmSamplesTable.TABLE_NAME,
                    DBProvider.AlarmSamplesTable.DEFAULT_SORT_ORDER, sortOrder);
            break;

        case WAKELOCK_ID:
            selectionArgs = setIdWhere(qb, uri,
                    DBProvider.WakeLockSamplesTable._ID, selectionArgs);
        case WAKELOCK:
            setQueryProperties(qb, mWakelockProjectionMap,
                    DBProvider.WakeLockSamplesTable.TABLE_NAME,
                    DBProvider.WakeLockSamplesTable.DEFAULT_SORT_ORDER,
                    sortOrder);
            break;

        case PROCESS_ID:
            selectionArgs = setIdWhere(qb, uri,
                    DBProvider.ProcessSamplesTable._ID, selectionArgs);
        case PROCESS:
            setQueryProperties(qb, mProcessProjectionMap,
                    DBProvider.ProcessSamplesTable.TABLE_NAME,
                    DBProvider.ProcessSamplesTable.DEFAULT_SORT_ORDER,
                    sortOrder);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);

        }
        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        // SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source
        // data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch (mUriMatcher.match(uri)) {
        case ALARM:
        case WAKELOCK:
        case PROCESS:
            return DBProvider.CONTENT_TYPE;
        case ALARM_ID:
        case WAKELOCK_ID:
        case PROCESS_ID:
            return DBProvider.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentvalues) {
        ContentValues values = null;
        String tableName = "";
        String nullColumn = "";

        if (null != contentvalues) {
            values = new ContentValues(contentvalues);
        } else {
            values = new ContentValues();
        }

        switch (mUriMatcher.match(uri)) {
        case ALARM:
            tableName = DBProvider.AlarmSamplesTable.TABLE_NAME;
            // if (values.containsKey(DBProvider.SessionsTable.STARTE_AVERAGE)
            // == false) {
            // values.put(DBProvider.SessionsTable.STARTE_AVERAGE, "");
            // }
            break;
        case WAKELOCK:
            tableName = DBProvider.WakeLockSamplesTable.TABLE_NAME;
            break;
        case PROCESS:
            tableName = DBProvider.ProcessSamplesTable.TABLE_NAME;
            break;
        default:
            break;
        }
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(tableName, null, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        // String finalWhere;
        int count;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理，注意下面用到的表名不要弄错了
        case ALARM_ID:
            where = DatabaseUtils.concatenateWhere(
                    DBProvider.AlarmSamplesTable._ID + " = "
                            + ContentUris.parseId(uri), where);
        case ALARM:
            count = db.delete(DBProvider.AlarmSamplesTable.TABLE_NAME, where,
                    whereArgs);
            break;
        case WAKELOCK_ID:
            where = DatabaseUtils.concatenateWhere(
                    DBProvider.WakeLockSamplesTable._ID + " = "
                            + ContentUris.parseId(uri), where);
        case WAKELOCK:
            count = db.delete(DBProvider.WakeLockSamplesTable.TABLE_NAME,
                    where, whereArgs);
            break;
        case PROCESS_ID:
            where = DatabaseUtils.concatenateWhere(
                    DBProvider.ProcessSamplesTable._ID + " = "
                            + ContentUris.parseId(uri), where);
        case PROCESS:
            count = db.delete(DBProvider.ProcessSamplesTable.TABLE_NAME, where,
                    whereArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String where,
            String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        String finalWhere;

        switch (mUriMatcher.match(uri)) {

        case ALARM_ID:
            // If URI is for a particular row ID, update is based on
            // incoming
            // data but modified to restrict to the given ID.
            where = DatabaseUtils.concatenateWhere(
                    DBProvider.AlarmSamplesTable._ID + " = "
                            + ContentUris.parseId(uri), where);
        case ALARM:
            // If URI is main table, update uses incoming where clause and
            // args.
            count = db.update(DBProvider.AlarmSamplesTable.TABLE_NAME, values,
                    where, whereArgs);
            break;

        case WAKELOCK_ID:
            // If URI is for a particular row ID, update is based on
            // incoming
            // data but modified to restrict to the given ID.
            where = DatabaseUtils.concatenateWhere(
                    DBProvider.WakeLockSamplesTable._ID + " = "
                            + ContentUris.parseId(uri), where);
        case WAKELOCK:
            // If URI is main table, update uses incoming where clause and
            // args.
            count = db.update(DBProvider.WakeLockSamplesTable.TABLE_NAME,
                    values, where, whereArgs);
            break;

        case PROCESS_ID:
            // If URI is for a particular row ID, update is based on
            // incoming
            // data but modified to restrict to the given ID.
            where = DatabaseUtils.concatenateWhere(
                    DBProvider.ProcessSamplesTable._ID + " = "
                            + ContentUris.parseId(uri), where);
        case PROCESS:
            // If URI is main table, update uses incoming where clause and
            // args.
            count = db.update(DBProvider.ProcessSamplesTable.TABLE_NAME,
                    values, where, whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
    }

    /**
     * 
     * @param qb
     * @param uri
     * @param _id
     * @param selectionArgs
     * @return
     */
    private String[] setIdWhere(SQLiteQueryBuilder qb, Uri uri, String _id,
            String[] selectionArgs) {
        qb.appendWhere(_id + "=?");
        return selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
    }

    /**
     * 
     * @param qb
     * @param projectionMap
     * @param tableName
     * @param defaultOrder
     * @param sortOrder
     * @return
     */
    private String setQueryProperties(SQLiteQueryBuilder qb,
            HashMap<String, String> projectionMap, String tableName,
            String defaultOrder, String sortOrder) {
        String orderBy = null;
        qb.setTables(tableName);
        qb.setProjectionMap(projectionMap);
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = defaultOrder;
        } else {
            orderBy = sortOrder;
        }
        return orderBy;
    }

    static {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        mUriMatcher.addURI(DBProvider.AlarmSamplesTable.AUTHORITY,
                DBProvider.AlarmSamplesTable.TABLE_NAME, ALARM);
        mUriMatcher.addURI(DBProvider.AlarmSamplesTable.AUTHORITY,
                DBProvider.AlarmSamplesTable.TABLE_NAME + "/#", ALARM_ID);

        mUriMatcher.addURI(DBProvider.WakeLockSamplesTable.AUTHORITY,
                DBProvider.WakeLockSamplesTable.TABLE_NAME, WAKELOCK);
        mUriMatcher.addURI(DBProvider.WakeLockSamplesTable.AUTHORITY,
                DBProvider.WakeLockSamplesTable.TABLE_NAME + "/#", WAKELOCK_ID);

        mUriMatcher.addURI(DBProvider.ProcessSamplesTable.AUTHORITY,
                DBProvider.ProcessSamplesTable.TABLE_NAME, PROCESS);
        mUriMatcher.addURI(DBProvider.ProcessSamplesTable.AUTHORITY,
                DBProvider.ProcessSamplesTable.TABLE_NAME + "/#", PROCESS_ID);

        mAlarmProjectionMap = new HashMap<String, String>();
        mAlarmProjectionMap.put(DBProvider.AlarmSamplesTable._ID,
                DBProvider.AlarmSamplesTable._ID);
        mAlarmProjectionMap.put(DBProvider.AlarmSamplesTable.PKG,
                DBProvider.AlarmSamplesTable.PKG);
        mAlarmProjectionMap.put(DBProvider.AlarmSamplesTable.SAMPLE_ID,
                DBProvider.AlarmSamplesTable.SAMPLE_ID);
        mAlarmProjectionMap.put(DBProvider.AlarmSamplesTable.COUNT,
                DBProvider.AlarmSamplesTable.COUNT);

        mWakelockProjectionMap = new HashMap<String, String>();
        mWakelockProjectionMap.put(DBProvider.WakeLockSamplesTable._ID,
                DBProvider.WakeLockSamplesTable._ID);
        mWakelockProjectionMap.put(DBProvider.WakeLockSamplesTable.SAMPLE_ID,
                DBProvider.WakeLockSamplesTable.SAMPLE_ID);
        mWakelockProjectionMap.put(DBProvider.WakeLockSamplesTable.TAG,
                DBProvider.WakeLockSamplesTable.TAG);
        mWakelockProjectionMap.put(DBProvider.WakeLockSamplesTable.TIME_LENGTH,
                DBProvider.WakeLockSamplesTable.TIME_LENGTH);

        mProcessProjectionMap = new HashMap<String, String>();
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable._ID,
                DBProvider.ProcessSamplesTable._ID);
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable.SAMPLE_ID,
                DBProvider.ProcessSamplesTable.SAMPLE_ID);
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable.PID,
                DBProvider.ProcessSamplesTable.PID);
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable.REL_STIME,
                DBProvider.ProcessSamplesTable.REL_STIME);
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable.REL_UPTIME,
                DBProvider.ProcessSamplesTable.REL_UPTIME);
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable.REL_UTIME,
                DBProvider.ProcessSamplesTable.REL_UTIME);
        mProcessProjectionMap.put(DBProvider.ProcessSamplesTable.NAME,
                DBProvider.ProcessSamplesTable.NAME);

    }
}
